package eva

import (
	"fmt"
	"github.com/xuri/excelize/v2"
	"github.com/zeromicro/go-zero/rest/httpx"
	xhttp "github.com/zeromicro/x/http"
	"net/http"
	"trusteva/app/eva/internal/logic/eva"
	"trusteva/app/eva/internal/svc"
	"trusteva/app/eva/internal/types"
)

func ExportWarningHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.ExportWarningRo
		if err := httpx.Parse(r, &req); err != nil {
			xhttp.JsonBaseResponseCtx(r.Context(), w, err)
			return
		}

		l := eva.NewExportWarningLogic(r.Context(), svcCtx)
		resp, err := l.ExportWarning(&req)
		if err != nil {
			xhttp.JsonBaseResponseCtx(r.Context(), w, err)
		} else {
			data := [][]string{
				{"Id", "CreatedAt", "AppName", "AppId", "DeviceId",
					"Memo", "DstIP", "DstPort", "Desc", "Level"},
			}

			for _, v := range resp.Data {
				data = append(data, []string{
					fmt.Sprintf("%d", v.Id),
					v.CreatedAt,
					v.AppName,
					v.AppId,
					v.DeviceId,
					v.Memo,
					v.DstIP,
					fmt.Sprintf("%d", v.DstPort),
					v.Desc,
					fmt.Sprintf("%d", v.Level),
				})
			}

			f := excelize.NewFile()
			defer f.Close()
			for idx, row := range data {
				cell, err := excelize.CoordinatesToCellName(1, idx+1)
				if err != nil {
					xhttp.JsonBaseResponseCtx(r.Context(), w, err)
					return
				}
				f.SetSheetRow("Sheet1", cell, &row)
			}
			_ = f.Write(w)
			// 设置响应头为Excel文件类型
			w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
			w.Header().Set("Content-Disposition", `attachment; filename="data.xlsx"`)
		}
	}
}
